package com.sbtr.business.utils;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;

/**
 * @author xrt
 * Created on 2020/9/17
 * 获取文件md5值
 */
@Slf4j
@Component
public class FileMd5Util {
    /**
     * 获取文件的MD5值
     * @param file 要获取MD5值的文件
     * @return 文件的MD5值
     */
    public String getFileMd5Value(Object file) {
        InputStream in = null;
        try {
            if (file instanceof MultipartFile) {
                in = ((MultipartFile) file).getInputStream();
            } else if (file instanceof File) {
                in = new FileInputStream((File) file);
            } else {
                log.error("不支持的文件类型");
                return null;
            }
            // 创建缓冲区
            byte[] buffer = new byte[2048];
            MessageDigest digest = MessageDigest.getInstance("MD5");
            // 读取文件内容并更新摘要对象
            while (true) {
                int len = in.read(buffer, 0, 2048);
                if (len != -1) {
                    digest.update(buffer, 0, len);
                } else {
                    break;
                }
            }
            in.close();
            byte[] md5Bytes = digest.digest();
            // 将字节数组转换为十六进制字符串
            StringBuffer hexValue = new StringBuffer();
            for (int i = 0; i < md5Bytes.length; i++) {
                int val = ((int) md5Bytes[i]) & 0xff;
                if (val < 16) {
                    hexValue.append("0");
                }
                hexValue.append(Integer.toHexString(val));
            }
            return hexValue.toString();
        } catch (Exception e) {
            log.error("获取文件md5失败");
        } finally {
            try {
                in.close();

            } catch (IOException ex) {
                log.error("关闭流异常", ex);
            }
        }
        return null;
    }

    @Test
    public void testGetFileMd5Value() throws Exception {
        File file = new File("D:\\诊断.xlsx");
        File file1 = new File("D:\\依然是诊断端文件.xlsx");
        File file2 = new File("E:\\诊断.xlsx");
        String md5Value = getFileMd5Value(file);
        String md5Value1 = getFileMd5Value(file1);
        String md5Value2 = getFileMd5Value(file2);
        System.err.println("md5Value.equals(md5Value1):"+md5Value.equals(md5Value1));
        System.err.println("md5Value.equals(md5Value2):"+md5Value.equals(md5Value2));
        System.err.println("md5Value1.equals(md5Value2):"+md5Value1.equals(md5Value2));
        System.out.println("文件的MD5值为：" + md5Value);
    }
}
